package com.ontheroad.db;

import com.ontheroad.db.dto.GDAODetailInfoDto;
import com.ontheroad.db.utils.GDAOToolsUtil;
import com.ontheroad.db.utils.VelocityUtil;
import com.ontheroad.db.utils.GDAOToolsConst;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.util.*;


public class GDAOToolsMain {

    /**
     * SQL 类型配置信息
     */
    public static Properties sqlTypeProperties;
    /**
     * DB数据库连接
     */
    private static Connection conn;
    /**
     * 配置信息
     */
    private static Properties configProperties;
    /**
     * 包名
     */
    private static final String PACKAGE = "";
    /**
     * 包名 对象类
     */
    private static final String MODEL_PACKAGE = "";
    /**
     * Model类 后缀
     */
    private static final String MODEL_CLASS = "Model";
    /**
     * 文件输出路径
     */
    private static final String OUT_PUT_PATH_JAVA = "/";
    /**
     * sql map 输出路径
     */
    private static final String DAO_OUT_PUT_PATH = "/";
    /**
     * dao信息list
     */
    private List<GDAODetailInfoDto> gdaoDetailInfoDtoList = new ArrayList<GDAODetailInfoDto>();
    /**
     * 分库前缀信息配列
     */
    private static final String[] SUB_LIBRARY_PREX = new String[]{"MYSQL_"};

    public static void main(String[] args) throws Exception {

        GDAOToolsMain toolsMain = new GDAOToolsMain();

        toolsMain.execute();

    }

    /**
     * 生成dao代码
     *
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private void execute() throws Exception {
        //初始化数据
        initData();

        Map<String, Object> paramMap = new HashMap<String, Object>();

        //设置sql map的模板名称
        paramMap.put("sqlMapClientTemplate", configProperties.getProperty("SQL_MAP_CLIENT_TEMPLATE"));

        for (int i = 0; i < SUB_LIBRARY_PREX.length; i++) {

            List<GDAODetailInfoDto> subLibDetailInfoDtoList = new ArrayList<GDAODetailInfoDto>();

            //获取需要生成的表
            String db_table_name_list = configProperties.getProperty(SUB_LIBRARY_PREX[i] + "DB_TABLE_NAME_LIST");
            //表对应的seq
            String db_table_seq_name_list = configProperties.getProperty(SUB_LIBRARY_PREX[i] + "DB_TABLE_SEQ_NAME_LIST");

            String[] tableArray = db_table_name_list.split(",");
            String[] tableSeqArray = null;

            if (!GDAOToolsUtil.isEmpty(db_table_seq_name_list)) {
                tableSeqArray = db_table_seq_name_list.split(",");
            }

            if (tableSeqArray != null && tableSeqArray.length > 0 && tableArray.length != tableSeqArray.length) {
                System.out.println("您设置的表名和表对应的seq名数量有误，请确认分库" + SUB_LIBRARY_PREX[i]);
                System.out.println("表数量：" + tableArray.length + "  表对应seq数量：" + tableSeqArray.length);
                return;
            }

            if (tableArray.length == 1 && StringUtils.isEmpty(tableArray[0])) {
                continue;

            } else {
                //数据库连接获取
                conn = GDAOToolsUtil.getConnection(SUB_LIBRARY_PREX[i], configProperties);
            }

            //读取模板配置信息
            String basePath = configProperties.getProperty("BASE_PATH");
            String dao_interface_template_file = basePath + configProperties.getProperty("DAO_INTERFACE_TEMPLATE_FILE");
            String dao_impl_template_file = basePath + configProperties.getProperty("DAO_IMPL_TEMPLATE_FILE");
            String dao_sql_map_template_file = basePath + configProperties.getProperty("DAO_SQL_MAP_TEMPLATE_FILE");
            String dao_model_template_file = basePath + configProperties.getProperty("DAO_MODEL_TEMPLATE_FILE");
            String datasource_name = configProperties.getProperty(SUB_LIBRARY_PREX[i] + "DATASOURCE_NAME");
            //分库文件输出路径
            String outputPath = configProperties.getProperty("OUT_PUT_PATH");

            String dao_sql_map_dao_template_file = basePath + configProperties.getProperty("DAO_SQL_MAP_DAO_TEMPLATE_FILE");
            String dao_sql_map_db_template_file = basePath + configProperties.getProperty("DAO_SQL_MAP_DB_TEMPLATE_FILE");
            String dao_sql_map_extend_template_file = basePath + configProperties.getProperty("DAO_SQL_MAP_EXTEND_TEMPLATE_FILE");

            for (int j = 0; tableArray != null && j < tableArray.length; j++) {
                if (!GDAOToolsUtil.isEmpty(tableArray[j])) {

                    try {
                        String tableSeq = null;

                        GDAODetailInfoDto detailInfoDto = GDAOToolsUtil.getGDAODetailInfo(conn, tableArray[j], tableSeq, sqlTypeProperties, configProperties.getProperty("MYSQL_DB_SCHEMA"));
                        detailInfoDto.setPackageName(PACKAGE);
                        detailInfoDto.setDatasourceName(datasource_name);
                        detailInfoDto.setTableName(tableArray[j].toLowerCase());

                        paramMap.put("detailInfoDto", detailInfoDto);

                        //生成dao代码
                        String dao_source = VelocityUtil.generateSourceWithCustomSource(dao_interface_template_file, paramMap,
                                GDAOToolsConst.CUSTOM_SOURCE.DAO, PACKAGE, detailInfoDto.getClassName() + "Mapper", outputPath + OUT_PUT_PATH_JAVA);
                        //生成dao impl 代码
//						String dao_impl_source = VelocityUtil.generateSourceWithCustomSource(dao_impl_template_file, paramMap, 
//								CUSTOM_SOURCE.DAO_IMPL, PACKAGE + IMPL_PACKAGE, detailInfoDto.getClassName() + DAO_CLASS + IMPL_CLASS, outputPath + OUT_PUT_PATH_JAVA);
                        //生成dao model 代码
                        String dao_model_source = VelocityUtil.generateSourceWithCustomSource(dao_model_template_file, paramMap,
                                GDAOToolsConst.CUSTOM_SOURCE.MODEL, PACKAGE + MODEL_PACKAGE, detailInfoDto.getClassName() + MODEL_CLASS, outputPath + OUT_PUT_PATH_JAVA);
                        //生成dao sql map 代码
                        String dao_sql_map_source = VelocityUtil.generateSourceWithCustomSource(dao_sql_map_template_file, paramMap,
                                GDAOToolsConst.CUSTOM_SOURCE.SQL_MAP, null, detailInfoDto.getBeanName(), outputPath + DAO_OUT_PUT_PATH);

                        //代码文件输出
                        VelocityUtil.printToJavaFile(PACKAGE, detailInfoDto.getClassName() + "Mapper", dao_source, outputPath + OUT_PUT_PATH_JAVA);
//						VelocityUtil.printToJavaFile(PACKAGE + IMPL_PACKAGE, detailInfoDto.getClassName() + DAO_CLASS + IMPL_CLASS, dao_impl_source, outputPath + OUT_PUT_PATH_JAVA);
                        VelocityUtil.printToJavaFile(PACKAGE + MODEL_PACKAGE, detailInfoDto.getClassName() + MODEL_CLASS, dao_model_source, outputPath + OUT_PUT_PATH_JAVA);
                        VelocityUtil.printToXMLFile(detailInfoDto.getClassName() + "Mapper", dao_sql_map_source, outputPath + DAO_OUT_PUT_PATH);
                        System.out.println(tableArray[j] + " : OK");

                        subLibDetailInfoDtoList.add(detailInfoDto);
                        gdaoDetailInfoDtoList.add(detailInfoDto);

                    } catch (Exception e) {
                        System.out.println("---------------" + tableArray[j] + "-----------------");
                        e.printStackTrace();
                        System.out.println("表" + tableArray[j] + "的代码无法生成  " + e.getMessage() + " 分库： " + SUB_LIBRARY_PREX[i]);
                    }
                }
            }
            System.out.println(outputPath);


        }

    }

    /**
     * 初始化数据
     *
     * @throws Exception
     */
    private void initData() throws Exception {

        //ToolsConfig配置文件读取
        configProperties = GDAOToolsUtil
                .readPropertiesByInputStream(getClass().getClassLoader()
                        .getResourceAsStream("ToolsConfig.properties"));

        //types配置文件读取
        sqlTypeProperties = GDAOToolsUtil
                .readPropertiesByInputStream(getClass().getClassLoader()
                        .getResourceAsStream("types.properties"));

    }

}
